package com.qf.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * --- 缘分让我们相遇乱世以外 ---
 *
 * @author SJY
 * @date 2024/11/8
 * @desc
 */
@WebFilter("/*")
public class LoginFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        System.out.println("--- 开始身份认证过滤 ---" );
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse resp = (HttpServletResponse) response;
        // 因为/* 拦截所有请求,但是需要放行登录和注册
        String uri = req.getRequestURI( );
        // System.out.println("uri = " + uri);

        if (uri.contains("login") || uri.contains("regist") || uri.contains("html")) {
            chain.doFilter(request,response);
        } else {
            HttpSession session = req.getSession( );
            Object user = session.getAttribute("user");
            if (user == null) {
                resp.sendRedirect("/loginv1.html");
            } else {
                chain.doFilter(request,response);
            }
        }
    }

    @Override
    public void destroy() {

    }
}
